<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.upup.fun","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="简单记录一下。">
<meta property="og:type" content="article">
<meta property="og:title" content="【完整的练手小项目】搭建自己的GPT服务">
<meta property="og:url" content="http://blog.upup.fun/2023/02/16/%E6%90%AD%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84GPT%E6%9C%8D%E5%8A%A1/index.html">
<meta property="og:site_name" content="猫头猫">
<meta property="og:description" content="简单记录一下。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.328888.xyz/2023/02/16/pne5k.jpeg">
<meta property="og:image" content="https://i.328888.xyz/2023/02/16/pnBkq.jpeg">
<meta property="og:image" content="https://i.328888.xyz/2023/02/16/pkXBP.png">
<meta property="og:image" content="https://i.328888.xyz/2023/02/16/pk1CU.png">
<meta property="og:image" content="https://i.328888.xyz/2023/02/16/p00Rt.jpeg">
<meta property="article:published_time" content="2023-02-16T12:30:25.000Z">
<meta property="article:modified_time" content="2023-02-16T15:58:29.714Z">
<meta property="article:author" content="猫头猫">
<meta property="article:tag" content="node.js">
<meta property="article:tag" content="小程序">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.328888.xyz/2023/02/16/pne5k.jpeg">

<link rel="canonical" href="http://blog.upup.fun/2023/02/16/%E6%90%AD%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84GPT%E6%9C%8D%E5%8A%A1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【完整的练手小项目】搭建自己的GPT服务 | 猫头猫</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">猫头猫</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-works">

    <a href="/works/" rel="section"><i class="fa fa-smile fa-fw"></i>小作品</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.upup.fun/2023/02/16/%E6%90%AD%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84GPT%E6%9C%8D%E5%8A%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="猫头猫">
      <meta itemprop="description" content="如果我是一只小猫咪，每天只要喵喵叫。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="猫头猫">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【完整的练手小项目】搭建自己的GPT服务
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-02-16 20:30:25" itemprop="dateCreated datePublished" datetime="2023-02-16T20:30:25+08:00">2023-02-16</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B0%8F%E5%B7%A5%E5%85%B7/" itemprop="url" rel="index"><span itemprop="name">小工具</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.8k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>
            <div class="post-description">简单记录一下。</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>本文首发于公众号【一只猫头猫】，平时记录一些自己做的好玩的东西，随便写写吧~</p>
<hr>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>很久没写小程序了，看到最近ChatGPT比较火，也想整个活玩一玩。于是花了一个周末做了个AI算命微信小程序，乐呵乐呵。先放一下最终的成品效果（小程序名字叫“赛博运势丨AI测命理”，微信直接搜也行）：</p>
<p><img src="https://i.328888.xyz/2023/02/16/pne5k.jpeg" alt=""><br><img src="https://i.328888.xyz/2023/02/16/pnBkq.jpeg" alt=""></p>
<h1 id="技术栈"><a href="#技术栈" class="headerlink" title="技术栈"></a>技术栈</h1><p>小程序端：Taro + React + sass<br>服务端：koa + rabbitmq + mongodb + redis</p>
<p>工程量不大，但麻雀虽小五脏俱全了属于是。本文会简单记录一下一些关键的步骤和实现思路，一些软件的安装服务就略过啦。接下来直入主题。</p>
<h1 id="整体思路"><a href="#整体思路" class="headerlink" title="整体思路"></a>整体思路</h1><h2 id="需求描述"><a href="#需求描述" class="headerlink" title="需求描述"></a>需求描述</h2><p>做一个AI算命的小程序，用户可以输入一些基础的个人信息，小程序需要根据个人信息推算出用户的其他信息，并根据推算信息查询运势。</p>
<h2 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h2><h3 id="运势生成"><a href="#运势生成" class="headerlink" title="运势生成"></a>运势生成</h3><p>首先OpenAI提供了官方的接口，去官网注册个账号，然后申领Key就可以直接通过API调用了。GPT系列目前有4种模型可以使用，分别是Davinci、Curie、Babbage和Ada，从前往后效果<strong>依次变差</strong>，但后边的速度<strong>会更快</strong>，价格会<strong>更便宜</strong>。我试了一下，后边3个模型在我给定的prompt上虽然很快，但表现稀烂，并且貌似只会回答英文，看来省钱是省不了了。</p>
<h3 id="前后端通信"><a href="#前后端通信" class="headerlink" title="前后端通信"></a>前后端通信</h3><p>请求OpenAI的部分肯定是得由服务端完成。具体来说，需要小程序端调用服务端的接口，然后由服务端向OpenAI发起请求，等待结果返回后再吐给前端。</p>
<p>既然是服务端，最基础的就是引入一个启动服务的框架，这里用的是<em>koa</em>。</p>
<p>考虑到土豆般的服务器，以及同时向OpenAI发起的请求数需要有一定的限制，因此需要引入一个消息队列来达到<strong>削峰</strong>的目的；要不然万一一不小心瞬间发送了大量请求，服务可能就崩了。这里使用了<em>rabbitmq</em>。<br>用消息队列还有个好处是<strong>解耦</strong>，换句话说，就是把<em>专门使用消息队列处理OpenAI请求</em>的进程和<em>直接向小程序端提供服务</em>的进程解耦开，这样其他应用也可以通过消息队列来直接使用GPT模型。</p>
<p>由于调OpenAI的<strong>过程很慢</strong>，假设我们从小程序端向服务器请求接口，由服务器发起一个调用OpenAI请求，我们不可能等个一两分钟一直等到这个请求返回结果。因此自然想到，需要把发起请求和查询结果分成两个接口，其中查询结果通过向服务器<strong>轮询</strong>的方式查询OpenAI是否已经给出结果。</p>
<p>既然是轮询，那肯定要保证<strong>数据在一段时间内能被查询到</strong>。那OpenAI返回的结果肯定要暂存在<strong>数据库</strong>中，简单起见，直接用<em>mongodb</em>就好了。考虑到轮询时候的查询性能，每次轮询都查询数据库太浪费了，因此中间需要加一层<em>redis</em>做缓冲。</p>
<p>到这里，整体的后端的技术选型就有了：<strong>koa + rabbitmq + mongodb + redis</strong>。至于小程序端，直接<strong>Taro + React + sass</strong>，和以前做的普通web项目体感没什么不同。</p>
<h2 id="工程架构"><a href="#工程架构" class="headerlink" title="工程架构"></a>工程架构</h2><p>大概画一个简单的示意图描述一下整体的架构：<br><img src="https://i.328888.xyz/2023/02/16/pkXBP.png" alt=""></p>
<h1 id="小程序端"><a href="#小程序端" class="headerlink" title="小程序端"></a>小程序端</h1><p>小程序端其实没什么可写的，没踩太多坑，就是普通的UI加了一些花里胡哨的动画。唯一就是分享图片的时候，搜了半天没搜到啥靠谱的，还以为小程序canvas上绘制base64图片很麻烦。最后看了下微信官方文档，发现和普通canvas差不多，简单封装个方法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">drawImage</span>(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">  canvas: <span class="built_in">any</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">  base64src: <span class="built_in">string</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">  dx: <span class="built_in">number</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">  dy: <span class="built_in">number</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">  width: <span class="built_in">number</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">  height: <span class="built_in">number</span></span></span></span><br><span class="line"><span class="params"><span class="function"></span>): <span class="title">Promise</span>&lt;<span class="title">void</span>&gt; </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!canvas || !img) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> image = canvas.createImage();</span><br><span class="line">  <span class="keyword">const</span> ctx: CanvasRenderingContext2D = canvas.getContext(<span class="string">&quot;2d&quot;</span>);</span><br><span class="line"></span><br><span class="line">  image.src = base64src;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> &#123;</span><br><span class="line">    image.onload = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      ctx.drawImage(image, dx, dy, width, height);</span><br><span class="line">      resolve();</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用这个直接在canvas上画就行了。</p>
<h1 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h1><p>根据上边的描述，服务端部分分成了两半，一半是专门用来向OpenAI发请求和处理消息的GPT服务；另一个是和小程序端打交道的Koa服务。</p>
<h2 id="GPT服务"><a href="#GPT服务" class="headerlink" title="GPT服务"></a>GPT服务</h2><p>这块也分成两部分来说，第一部分就是怎么给OpenAI发请求调用GPT模型，第二部分是怎么使用消息队列和数据库。</p>
<h3 id="调用GPT模型"><a href="#调用GPT模型" class="headerlink" title="调用GPT模型"></a>调用GPT模型</h3><p>这里用到了chatgpt库。这个库使用到了node18的原生fetch，因此它的package.json里有这么一行：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;engines&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;node&quot;</span>: <span class="string">&quot;&gt;=18&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>也就是低于18.x版本的node环境下装这个包可能会报错。但是没关系，可以使用：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn add chatgpt --ignore-engines</span><br></pre></td></tr></table></figure><br>来忽略环境的不匹配，在实际调用的时候引个polyfill就好了。引入polyfill有两种方式：</p>
<ul>
<li>方法一： 安装node-fetch，然后给全局fetch赋值：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> nodeFetch <span class="keyword">from</span> <span class="string">&#x27;node-fetch&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; ChatGPTAPI &#125; <span class="keyword">from</span> <span class="string">&quot;chatgpt&quot;</span>;</span><br><span class="line"></span><br><span class="line">globalThis.fetch = nodeFetch;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> api = <span class="keyword">new</span> ChatGPTAPI(&#123;</span><br><span class="line">    <span class="attr">apiKey</span>: YOUR_OPENAI_KEY,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></li>
<li>方法二： 这个库的最新版在创建GPT实例的时候可以传入一个fetch参数，也就是：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> nodeFetch <span class="keyword">from</span> <span class="string">&#x27;node-fetch&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; ChatGPTAPI &#125; <span class="keyword">from</span> <span class="string">&quot;chatgpt&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> api = <span class="keyword">new</span> ChatGPTAPI(&#123;</span><br><span class="line">    <span class="attr">apiKey</span>: YOUR_OPENAI_KEY,</span><br><span class="line">    <span class="attr">fetch</span>: nodeFetch</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>接下来就可以通过sendMessage方法去发起请求了：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">api.sendMessage(<span class="string">&quot;假如你是一只小狗，你会对我说什么呢？&quot;</span>).then(<span class="built_in">console</span>.log);</span><br></pre></td></tr></table></figure><br>等一会之后，就可以看到ChatGPT的回复：</p>
<p><img src="https://i.328888.xyz/2023/02/16/pk1CU.png" alt=""></p>
<h3 id="消息队列"><a href="#消息队列" class="headerlink" title="消息队列"></a>消息队列</h3><p>安装rabbitmq的过程 网上教程一堆，就略过了~假定消息队列服务已经启动好了，直接说在node中的使用。首先安装一下amqplib库。<br>安装完成之后，第一步是<strong>连接消息队列服务</strong>：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; connect &#125; <span class="keyword">from</span> <span class="string">&#x27;amqplib&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注意后边带一个heartbeat参数，要不然时间长了无心跳连接可能会被关闭</span></span><br><span class="line"><span class="keyword">let</span> connection = <span class="keyword">await</span> connect(<span class="string">&quot;amqp://127.0.0.1?heartbeat=180&quot;</span>);</span><br></pre></td></tr></table></figure><br>第二步是<strong>创建一个channel</strong>。建立连接以后，所有的消息队列有关的amqp协议操作，都会通过channel完成：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> channel = <span class="keyword">await</span> connection.createChannel();</span><br></pre></td></tr></table></figure><br>第三步是<strong>创建一个交换机</strong>，并为它绑定一个队列。在这里采用的是直连，通过duration开启了持久化，从而下次重启的时候，队列中的内容还可以恢复：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> exchangeName = <span class="string">&quot;chat-gpt-exchange&quot;</span>;</span><br><span class="line"><span class="keyword">const</span> key = <span class="string">&quot;request-queue&quot;</span>;</span><br><span class="line"><span class="keyword">await</span> channel.assertExchange(exchangeName, <span class="string">&#x27;direct&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">durable</span>: <span class="literal">true</span>, <span class="comment">// 持久化</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 创建名为key的队列</span></span><br><span class="line"><span class="keyword">await</span> channel.assertQueue(key);</span><br><span class="line"><span class="comment">// 绑定队列，三个参数分别为：队列名，交换机名，路由名</span></span><br><span class="line"><span class="keyword">await</span> channel.bindQueue(key, exchangeName, key);</span><br></pre></td></tr></table></figure><br>第四步是<strong>削峰和处理逻辑</strong>的部分。需要注意，noAck需要设置为false，一直等到消息处理完成手动触发ack，这时才会在队列中取下一个。<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 每次从消息队列中按顺序取出10个进行消费</span></span><br><span class="line"><span class="keyword">await</span> channel.prefetch(<span class="number">10</span>);</span><br><span class="line"><span class="comment">// 具体的消费方法，msg是从队列中取出的内容，这里我传来的是一个json</span></span><br><span class="line"><span class="keyword">await</span> channel.consume(key, <span class="keyword">async</span> msg =&gt; &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> content = msg.content.toString();</span><br><span class="line">        <span class="keyword">const</span> jsonContent = <span class="built_in">JSON</span>.parse(content);</span><br><span class="line">        <span class="keyword">const</span> result = <span class="keyword">await</span> chatgptApi.sendMessage(jsonContent.msg, jsonContent.options);</span><br><span class="line">        <span class="keyword">const</span> id = jsonContent.id;</span><br><span class="line">        <span class="comment">// 写入redis, ttl设置为10分钟（直接使用redis包，调用redis.createClient然后就可以直接调了）</span></span><br><span class="line">        redisClient.set(<span class="string">`<span class="subst">$&#123;<span class="keyword">namespace</span>&#125;</span><span class="subst">$&#123;id&#125;</span>`</span>, <span class="built_in">JSON</span>.stringify(result), &#123;</span><br><span class="line">            <span class="attr">EX</span>: <span class="number">600</span></span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 写入mongodb，略过了</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        channel.ack(msg);</span><br><span class="line">    &#125; <span class="keyword">catch</span> &#123;</span><br><span class="line">    &#125;</span><br><span class="line">    channel.ack(msg);</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    <span class="attr">noAck</span>: <span class="literal">false</span>,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<h3 id="数据库"><a href="#数据库" class="headerlink" title="数据库"></a>数据库</h3><p>为了减少服务器的负担，存储在mongodb和redis中的数据都做了定时删除。操作mongodb用的是mongoose库，定时删除的方法也很简单，在创建Schema的时候设置一下createAt属性就好了：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> resultsSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    <span class="comment">/** 请求ID **/</span></span><br><span class="line">    <span class="attr">reqId</span>: &#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="built_in">String</span>,</span><br><span class="line">        <span class="attr">required</span>: <span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">/** 请求结果 */</span></span><br><span class="line">    <span class="attr">result</span>: &#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="built_in">Object</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">createdAt</span>: &#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="built_in">Date</span>,</span><br><span class="line">        <span class="attr">default</span>: <span class="built_in">Date</span>.now,</span><br><span class="line">        <span class="attr">index</span>: &#123;</span><br><span class="line">            <span class="attr">expires</span>: <span class="string">&#x27;1h&#x27;</span> <span class="comment">// 设置1小时后自动过期，过期后会自动删除</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<h2 id="Koa服务"><a href="#Koa服务" class="headerlink" title="Koa服务"></a>Koa服务</h2><p>这个服务就是卡在中间，作用就是处理来自小程序端的请求，不停的往消息队列里面塞信息，不停的查询redis和数据库。具体来说，除去和微信小程序打交道的部分，主要的接口就两个：start（发起调用GPT的申请）和query（查询请求结果）</p>
<h3 id="开始查询"><a href="#开始查询" class="headerlink" title="开始查询"></a>开始查询</h3><p>这里的逻辑和上边消费的部分其实有些类似，依然是创建连接、创建channel、创建队列，不过是由消费变成了生产：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; connect &#125; <span class="keyword">from</span> <span class="string">&#x27;amqplib&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> connection = <span class="keyword">await</span> connect(<span class="string">&quot;amqp://127.0.0.1?heartbeat=180&quot;</span>);</span><br><span class="line"><span class="keyword">let</span> channel = <span class="keyword">await</span> connection.createChannel();</span><br><span class="line"><span class="keyword">const</span> exchangeName = <span class="string">&quot;chat-gpt-exchange&quot;</span>;</span><br><span class="line"><span class="keyword">const</span> key = <span class="string">&quot;request-queue&quot;</span>;</span><br><span class="line"><span class="keyword">await</span> channel.assertExchange(exchangeName, <span class="string">&#x27;direct&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">durable</span>: <span class="literal">true</span>, <span class="comment">// 持久化</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 创建名为key的队列</span></span><br><span class="line"><span class="keyword">await</span> channel.assertQueue(key);</span><br><span class="line"><span class="comment">// 绑定队列，三个参数分别为：队列名，交换机名，路由名</span></span><br><span class="line"><span class="keyword">await</span> channel.bindQueue(key, exchangeName, key);</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 以上代码和消费端一模一样 */</span></span><br><span class="line"><span class="keyword">const</span> reqId = <span class="string">&#x27;xxx&#x27;</span>;</span><br><span class="line"><span class="comment">// 生产消息</span></span><br><span class="line">channel?.publish(exchangeName, key, Buffer.from(<span class="built_in">JSON</span>.stringify(&#123;</span><br><span class="line">    <span class="attr">reqId</span>: reqId,</span><br><span class="line">    <span class="attr">msg</span>: <span class="string">&#x27;假如你是一只小狗，你会对我说什么？&#x27;</span>,</span><br><span class="line">    <span class="attr">options</span>: &#123;&#125; <span class="comment">// chatgpt的options参数</span></span><br><span class="line">&#125;)));</span><br><span class="line"><span class="comment">// 在redis中打个标记</span></span><br><span class="line">redisClient.set(reqId, <span class="number">1</span>, &#123;</span><br><span class="line">    <span class="attr">EX</span>: <span class="number">600</span> <span class="comment">// 过期时间</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>总结起来使用消息队列也不是很复杂。需要注意的是，在生产消息的同时给redis中打个标记，意思是这条请求已经在处理中了。如果不这样的话，在下边轮询的时候在redis中以reqId为key获取到的值是null，会使得每次查询都无法命中redis，始终穿透到mongodb数据库。这样就失去使用redis的意义了。</p>
<h3 id="查询结果"><a href="#查询结果" class="headerlink" title="查询结果"></a>查询结果</h3><p>查询结果的代码就不啰嗦了，总之：第一步查redis，redis中记录了请求的状态；如果没有就查mongodb，如果mongodb还没有，那就证明这个请求已经过期了，直接返回失败。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>总结起来，这一个练手的小项目还是用到了不少知识的。通过以上描述，也可以大概搭起一个比较稳定（虽然速度堪忧）的chatgpt服务。之后还可以做什么就自由发挥了~</p>
<p>最后贴一下这个小程序的二维码，感兴趣的可以去试试算个运势~（仅供娱乐~ 5分钟内应该会返回结果，比较慢）</p>
<p><img src="https://i.328888.xyz/2023/02/16/p00Rt.jpeg" alt=""> </p>

    </div>

    
    
    
        <div class="reward-container">
  <div>嘻嘻</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="猫头猫 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="猫头猫 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/images/wechat_channel.jpg">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/node-js/" rel="tag"><i class="fa fa-tag"></i> node.js</a>
              <a href="/tags/%E5%B0%8F%E7%A8%8B%E5%BA%8F/" rel="tag"><i class="fa fa-tag"></i> 小程序</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2023/01/09/ReactNative%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E2%80%94%E2%80%94%E6%8B%96%E6%8B%BD%E6%8E%92%E5%BA%8F/" rel="prev" title="【干货】React Native性能优化——长列表拖拽排序">
      <i class="fa fa-chevron-left"></i> 【干货】React Native性能优化——长列表拖拽排序
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/02/20/%E7%94%A8ChatGPT%E5%92%8CAI%E7%BB%98%E7%94%BB%E5%81%9A%E4%B8%80%E4%B8%AA%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F/" rel="next" title="用ChatGPT和AI绘画做一个微信小程序">
      用ChatGPT和AI绘画做一个微信小程序 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=477844082&auto=1&height=66"></iframe>

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8A%80%E6%9C%AF%E6%A0%88"><span class="nav-number">2.</span> <span class="nav-text">技术栈</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%95%B4%E4%BD%93%E6%80%9D%E8%B7%AF"><span class="nav-number">3.</span> <span class="nav-text">整体思路</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%9C%80%E6%B1%82%E6%8F%8F%E8%BF%B0"><span class="nav-number">3.1.</span> <span class="nav-text">需求描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%80%9D%E8%B7%AF"><span class="nav-number">3.2.</span> <span class="nav-text">实现思路</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%90%E5%8A%BF%E7%94%9F%E6%88%90"><span class="nav-number">3.2.1.</span> <span class="nav-text">运势生成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1"><span class="nav-number">3.2.2.</span> <span class="nav-text">前后端通信</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E7%A8%8B%E6%9E%B6%E6%9E%84"><span class="nav-number">3.3.</span> <span class="nav-text">工程架构</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%AB%AF"><span class="nav-number">4.</span> <span class="nav-text">小程序端</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="nav-number">5.</span> <span class="nav-text">服务端</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#GPT%E6%9C%8D%E5%8A%A1"><span class="nav-number">5.1.</span> <span class="nav-text">GPT服务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E7%94%A8GPT%E6%A8%A1%E5%9E%8B"><span class="nav-number">5.1.1.</span> <span class="nav-text">调用GPT模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97"><span class="nav-number">5.1.2.</span> <span class="nav-text">消息队列</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-number">5.1.3.</span> <span class="nav-text">数据库</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Koa%E6%9C%8D%E5%8A%A1"><span class="nav-number">5.2.</span> <span class="nav-text">Koa服务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%80%E5%A7%8B%E6%9F%A5%E8%AF%A2"><span class="nav-number">5.2.1.</span> <span class="nav-text">开始查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9F%A5%E8%AF%A2%E7%BB%93%E6%9E%9C"><span class="nav-number">5.2.2.</span> <span class="nav-text">查询结果</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="猫头猫"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">猫头猫</p>
  <div class="site-description" itemprop="description">如果我是一只小猫咪，每天只要喵喵叫。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/maotoumao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;maotoumao" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:lhx_xjtu@163.com" title="E-Mail → mailto:lhx_xjtu@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">猫头猫</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">91k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:22</span>
   | <a href="http://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备20005224号-2 </a>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
